import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const routes = [
  // 1️⃣ 全屏登录/注册/找回（不带侧边栏）
  { path: '/login',         name: 'Login',         component: () => import('@/views/auth/Login.vue') },
  { path: '/register',      name: 'Register',      component: () => import('@/views/auth/Register.vue') },
  { path: '/forgot',        name: 'Forgot',        component: () => import('@/views/auth/ForgotPassword.vue') },
  { path: '/reset',         name: 'Reset',         component: () => import('@/views/auth/ResetPassword.vue') },

  // 2️⃣ 主框架（带侧边栏）
  {
    path: '/',
    component: () => import('@/components/Layout/Layout.vue'), 
    redirect: '/dashboard',
    children: [
      {
        path: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { title: '仪表盘', icon: 'carbon:dashboard' }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/profile/Profile.vue'),
        meta: { title: '个人中心', icon: 'carbon:user' }
      },
      {
        path: '/system',
        name: 'System',
        redirect: '/system/users',
        meta: { title: '系统管理', icon: 'carbon:settings' },
        children: [
          {
            path: '/system/users',
            name: 'SystemUsers',
            component: () => import('@/views/system/Users.vue'),
            meta: { title: '用户管理' }
          },
          {
            path: '/system/role',
            name: 'SystemRole',
            component: () => import('@/views/system/Role.vue'),
            meta: { title: '角色管理' }
          },
          {
            path: '/system/permission',
            name: 'SystemPermission',
            component: () => import('@/views/system/Permission.vue'),
            meta: { title: '权限管理' }
          },
          {
            path: '/system/menu',
            name: 'SystemMenu',
            component: () => import('@/views/system/menu.vue'),
            meta: { title: '菜单管理' }
          },
          {
            path: '/system/operationLog',
            name: 'SystemOperationLog',
            component: () => import('@/views/system/OperationLog.vue'),
            meta: { title: '日志管理' }
          },
          {
            path: '/system/config',
            name: 'SystemConfig',
            component: () => import('@/views/system/SystemConfig.vue'),
            meta: { title: '系统配置' }
          }
        ]
      },

      { 
        path: '/404', 
        name: 'NotFound', 
        component: () => import('@/views/error/404.vue') 
      }
    ]
  },

  // 3️⃣ 兜底 404
  { path: '/:pathMatch(.*)*', redirect: '/404' }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 全局守卫：已登录不能回登录/找回页；未登录只能访问白名单
const whiteList = ['/login', '/register', '/forgot', '/reset']

router.beforeEach((to, from, next) => {
  console.log('🚀 路由导航:', { from: from.path, to: to.path })
  
  const token = localStorage.getItem('token')
  const userInfo = localStorage.getItem('userInfo')
  
  // 验证token和用户信息的有效性
  let hasValidAuth = false
  if (token && userInfo) {
    try {
      const parsedUserInfo = JSON.parse(userInfo)
      // 检查是否是有效的用户信息（不是开发环境自动生成的）
      hasValidAuth = !!(parsedUserInfo && parsedUserInfo.id && !parsedUserInfo.id.startsWith('dev-user-id-'))
    } catch (error) {
      console.warn('用户信息解析失败:', error)
      hasValidAuth = false
    }
  }

  // 如果访问的是白名单页面（登录、注册等）
  if (whiteList.includes(to.path)) {
    if (hasValidAuth) {
      // 已登录用户访问登录页，重定向到首页
      console.log('🔄 已登录用户访问登录页，重定向到首页')
      next('/')
    } else {
      // 未登录用户访问登录页，允许访问
      console.log('✅ 允许访问白名单页面:', to.path)
      next()
    }
  } else {
    // 访问需要认证的页面
    if (hasValidAuth) {
      // 已登录，允许访问
      console.log('✅ 已登录，允许访问:', to.path)
      next()
    } else {
      // 未登录或认证信息无效，清理localStorage并重定向到登录页
      console.log('❌ 未登录或认证信息无效，重定向到登录页')
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userId')
      next('/login')
    }
  }
})

export default router